package org.batatasframework.support.format;

import java.util.ArrayList;
import java.util.List;

import org.batatasframework.common.StringLimit;
import org.batatasframework.support.type.OptionalIterable;
import org.springframework.util.Assert;

/**
 * 限制字符串的内容范围
 * @author jackson
 *
 */
public class StringLimitsFormat implements OptionalIterable, StringLimit{
	
	/** 是否严格限制值必须属于定义的范围内  */
	private final boolean strict;
	private final String[] limits;
	private final String nullName;
	private boolean nullable = true;
	
	public StringLimitsFormat(boolean strict, String nullValue, String... limits){
		Assert.notEmpty(limits, "限制列表不能为空！");
		
		this.strict = strict;
		this.nullName = nullValue;
		this.limits = limits;
	}

	public StringLimitsFormat(String... limits){
		this(false, "", limits);
	}
	
	public String format(String str){
		if(strict){
			for(String limit : limits){
				
				if(limit == null && str == null) break;
				
				if(limit != null && limit.equals(str)){
					return str;
				}
			}
			return nullable ? nullName : "";
		}
		return str;
	}
	
	public String getNullName() {
		return nullName;
	}
	
	public String[] getLimits() {
		return limits;
	}
	
	/**
	 * 统计的时候是否统计空值
	 */
	public boolean isNullable(){
		return nullable;
	}

	@Override
	public List<? extends OptionalEntry> getSources() {
		List<StringLimitOptionalEntry> items = new ArrayList<>();
		for(String it : limits){
			items.add(new StringLimitOptionalEntry(it));
		}
		return items;
	}
	
	private class StringLimitOptionalEntry implements OptionalEntry{
		private final String name;
		
		private StringLimitOptionalEntry(String name){
			this.name = name;
		}
		
		@Override
		public String getName() {
			return name;
		}
		
		@Override
		public Object getValue() {
			return name;
		}
	}
}
